local desc_huanhua = [[
  # 幻化之战简介

  ---

  ## 身份说明

  游戏由2~10名玩家进行，玩家们各自为战，力求活到最后！

  ---

  ## 游戏目标

  杀死所有阵营与你不同的角色
  
  ---

  ## 击杀奖惩
  
  当一名角色死亡时，杀死其的角色摸三张牌。

  ---

  ## 新生

  所有角色以自己的头像为武将，体力上限、体力值会被调整到4点、护甲会归零。

  ---

  ## 普通模式（默认）

  每名角色通过造成伤害来获得「灵力」，通过消耗「灵力」获得技能（最多3个，超过则由角色选择一个失去）和摸牌。

  游戏开始时，每名角色各获得2枚「灵力」，从3个随机技能中选1个获得（不计入上限），或摸两张牌。

  每当你造成1点伤害后，你获得1枚「灵力」。

  回合开始时，你可以移除2枚「灵力」，从3个随机技能中选1个获得。

  出牌阶段限一次，你可以移除任意枚「灵力」，摸等量的牌。

  ---

  ## 狂暴模式（开启房间的双将选项解锁）

  每轮开始时，所有角色各自从3个随机技能中选1个获得，或者摸两张牌。

]]

local H = require "packages/activities/HuanhuaFunc"
local U = require "packages/utility/utility"

  -- 模式逻辑
local huanhua_getLogic = function()
  ---@class GameLogic
  local huanhua_logic = GameLogic:subclass("huanhua_logic")
  -- 大混战呗
  function huanhua_logic:assignRoles()
    local room = self.room
    local n = #room.players
    for i = 1, n do
      local p = room.players[i]
      p.role = "hidden"
      p.role_shown = true
      room:broadcastProperty(p, "role")
      --p.role = p._splayer:getScreenName() --结算显示更好，但身份图标疯狂报错
    end
    self.start_role = "hidden"
    -- for adjustSeats
    room.players[1].role = "lord"
  end
  -- 皮套自备
  function huanhua_logic:chooseGenerals()
    local room = self.room
    local lord = room:getLord()
    room.current = lord
    lord.role = "hidden"
    local players = room.players
    for _, p in ipairs(players) do
      local avatar = p._splayer:getAvatar()
      if avatar == "anjiang" then avatar = "guanyu" end
      local avatar_general = Fk.generals[avatar] or Fk.generals["guanyu"]
      room:setPlayerGeneral(p, avatar_general.name, true)
      room:broadcastProperty(p, "general")
      room:setPlayerProperty(p, "shield", 0)
      room:setPlayerProperty(p, "maxHp", 4)
      room:setPlayerProperty(p, "hp", 4)
    end
    room:doBroadcastNotify("ShowToast", Fk:translate("huanhua_intro"))
  end
  -- 体力初始化（上面已经做了）
  function huanhua_logic:broadcastGeneral()

  end
  -- 技能初始化
  function huanhua_logic:attachSkillToPlayers()
    
  end

  return huanhua_logic
end

-- 修改一名角色的灵力数
---@param player ServerPlayer
---@param num integer
local function addSiritualPower(player, num)
  if num > 0 then
    player.room:addPlayerMark(player, "@!spiritualPower", num)
  else
    player.room:removePlayerMark(player, "@!spiritualPower", -num)
  end
end

-- 获知一名角色的灵力数
---@param player Player
---@return integer
local function getSpiritualPower(player)
  return player:getMark("@!spiritualPower")
end

-- 获知一名角色的聚灵技能
---@param player Player
---@return string[]
local function getJulingSkills(player)
  return player:getTableMark( "JulingSkills")
end

-- 设置一名角色的聚灵技能
---@param player ServerPlayer
---@param skill string
local function setJulingSkill(player, skill)
  local room = player.room
  local juling_skills = getJulingSkills(player)
  if #juling_skills == 3 then
    local tolose = room:askForChoice(player, juling_skills, "spiritualPower&", "#JulingLose", true) or juling_skills[1]
    table.removeOne(juling_skills, tolose)
    room:handleAddLoseSkills(player, "-"..tolose)
  end
  room:handleAddLoseSkills(player, skill)
  table.insert(juling_skills, skill)
  room:setPlayerMark(player, "JulingSkills", juling_skills)
  local translate = table.map(juling_skills, function(s) return Fk:translate(s) end)
  room:setPlayerMark(player, "@JulingSkills", "<font color='gold'>" .. table.concat(translate, " ") .. "</font>")
end

-- 聚灵！
---@param player ServerPlayer
local function doJuling(player)
  local room = player.room
  local choices, beta_choices = H.getSkills(room, 3), {}
  addSiritualPower(player, -2)
  if getSpiritualPower(player) > 0 then
    table.insert(choices, "HuanhuaRefresh")
  end
  local choice = room:askForChoice(player, choices, "spiritualPower&", "#Juling-choose", true)
  if not choice then choice = choices[1] end
  if choice == "HuanhuaRefresh" then
    addSiritualPower(player, -1)
    beta_choices = H.getSkills(room, 3)
    choice = room:askForChoice(player, beta_choices, "spiritualPower&", "#Juling-choose", true)
  end
  if not choice then choice = choices[1] end
  setJulingSkill(player, choice)
  for _, t in ipairs{choices, beta_choices} do
    H.returnToSkillPool(room, table.filter(t, function(s) return s ~= "HuanhuaRefresh" and s ~= choice end))
  end
end

local juling = fk.CreateActiveSkill{
  name = "spiritualPower&",
  anim_type = "drawcard",
  target_num = 0,
  prompt = "#JulingDraw",
  interaction = function()
    return UI.Spin { from = 1, to = getSpiritualPower(Self), }
  end,
  can_use = function(self, player)
    return getSpiritualPower(player) > 0 and player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  card_filter = Util.FalseFunc,
  target_filter = Util.FalseFunc,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local tolose = self.interaction.data
    if not tolose then return end
    addSiritualPower(player, -tolose)
    player:drawCards(tolose, self.name)
  end,
}

local juling_trigger = fk.CreateTriggerSkill{
  name = "#juling_trigger",
  events = {fk.TurnStart},
  priority = 0.001,
  can_trigger = function (self, event, target, player, data)
    return target == player and getSpiritualPower(player) > 1
  end,
  on_use = function (self, event, target, player, data)
    doJuling(player)
  end,
}

juling:addRelatedSkill(juling_trigger)
Fk:addSkill(juling)

  -- 幻化之战[规则]
local huanhua_rule = fk.CreateTriggerSkill{
  name = "#huanhua_rule",
  priority = 0.001,
  refresh_events = {fk.GameStart, fk.GameOverJudge, fk.Deathed, fk.RoundStart, fk.Damage},
  can_refresh = function(self, event, target, player, data)
    return target == player
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    local isUpgrade = room.settings.enableDeputy
    -- 击杀奖励
    if event == fk.Deathed then
      local body = room:getPlayerById(data.who)
      if data.damage then
        local killer = data.damage.from
        if killer and not killer.dead then
          killer:drawCards(3, "kill")
        end
      end
    -- 造成伤害获得灵力（普通模式）
    elseif event == fk.Damage then
      if not isUpgrade and target == player then
        addSiritualPower(player, data.damage)
      end
    -- 每轮幻化(强化模式)
    elseif event == fk.RoundStart then
      if isUpgrade then
        room:doBroadcastNotify("ShowToast", Fk:translate("huanhua_start"))
        H.doHuanhua(room)
      end
    -- 游戏结束判定
    elseif event == fk.GameOverJudge then
      room:setTag("SkipGameRule", true)
      if #room.alive_players == 1 then
        local winner = Fk.game_modes[room.settings.gameMode]:getWinner(player)
        if winner ~= "" then
          room:gameOver(winner)
          return true
        end
      end
    -- 构建技能池
    elseif event == fk.GameStart then
      H.createSkillPool(room)
      if not isUpgrade then
        room:setBanner("@HuanhuaMode", "#NormalHuanhuaMode")
        for _, p in ipairs(room:getAllPlayers()) do
          room:handleAddLoseSkills(p, "spiritualPower&")
          addSiritualPower(p, 2)
        end
        H.doHuanhua(room)
      else
        room:setBanner("@HuanhuaMode", "#BawrolHuanhuaMode")
      end
    end
  end,
}
Fk:addSkill(huanhua_rule)

--人数限制
local huanhua_mode = fk.CreateGameMode{
  name = "huanhua_mode",
  minPlayer = 2,
  maxPlayer = 10,
  rule = huanhua_rule,
  logic = huanhua_getLogic,
  surrender_func = function(self, playedTime)
    local surrenderJudge = { { text = "#left two alive", passed = #Fk:currentRoom().alive_players == 2 } }
    return surrenderJudge
  end,
  winner_getter = function(self, victim)
    local room = victim.room
    local alive = table.filter(room.alive_players, function(p)
      return not p.surrendered
    end)
    if #alive > 1 then return "" end
    alive[1].role = "renegade" --生草
    return "renegade"
  end,
}

Fk:loadTranslationTable{
  ["huanhua_mode"] = "幻化之战",
  [":huanhua_mode"] = desc_huanhua,
  ["#huanhua_rule"] = "幻化之战",
  ["huanhua_start"] = "幻幻无穷，生生不息",
  ["huanhua_intro"] = "运用巧妙的技能组合，击败所有对手吧！",
  ["#left two alive"] = "仅剩两名角色存活",

  ["spiritualPower&"] = "聚灵",
  [":spiritualPower&"] = "回合开始时，你可以移除2枚「灵力」，从3个随机技能中选一个获得；"
  .."出牌阶段限一次，你可以移除任意枚「灵力」，摸等量的牌。",
  ["#juling_trigger"] = "聚灵",
  ["HuanhuaRefresh"] = "刷新选项",
  [":HuanhuaRefresh"] = "消耗1枚「灵力」，刷新选项！",
  ["#Juling-choose"] = "聚灵：选择以下一个技能获得",
  ["@JulingSkills"] = "",
  ["#JulingLose"] = "聚灵：技能数量超出限制，选择以下1个已有的技能失去",
  ["#JulingDraw"] = "聚灵：可以移除任意枚「灵力」，摸等量的牌",

  ["@HuanhuaMode"] = "幻化",
  ["#NormalHuanhuaMode"] = "通常模式",
  ["#BawrolHuanhuaMode"] = "狂暴模式",
}

return huanhua_mode
